package com.example.caoben_back.contoller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.caoben_back.entity.po.Comment;
import com.example.caoben_back.entity.po.User;
import com.example.caoben_back.entity.vo.Result;
import com.example.caoben_back.service.ICommentService;
import com.example.caoben_back.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private ICommentService commentService;
    
    // 发布评论
    @PostMapping("/publish")
    public Result<Integer> publishComment(@RequestBody Comment comment,
                                         HttpServletRequest request) {
        // 从token中解析用户信息
        User user = TokenUtil.getUserFromRequest(request);
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Integer userId = user.getUserId();
        
        comment.setUserId(userId);
        comment.setPublishTime(LocalDateTime.now());
        commentService.save(comment);
        return Result.success(comment.getCommentId());
    }

    // 获取楼层下的评论列表
    @GetMapping("/list")
    public Result<Map<String, Object>> getFloorComments(@RequestParam Integer floorId,
                                                       @RequestParam Integer page,
                                                       @RequestParam Integer size) {
        Page<Comment> commentPage = commentService.page(new Page<>(page, size),
                new QueryWrapper<Comment>().eq("floor_id", floorId).orderByAsc("comment_id"));
        Map<String, Object> data = new HashMap<>();
        data.put("list", commentPage.getRecords());
        data.put("total", commentPage.getTotal());
        return Result.success(data);
    }

    // 删除评论
    @DeleteMapping("/delete")
    public Result<Boolean> deleteComment(@RequestParam Integer commentId) {
        return Result.success(commentService.removeById(commentId));
    }
}